package com.example.exp_9;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    Button start,stop,sum;
    EditText input;
    MathService.MyBinder binder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        start = findViewById(R.id.btnstart);
        stop = findViewById(R.id.btnstop);
        sum = findViewById(R.id.btnsum);

        input = findViewById(R.id.ednumber);


        ServiceConnection connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                binder=(MathService.MyBinder)iBinder;
            }
            @Override
            public void onServiceDisconnected(ComponentName componentName) {

            }
        };

        Intent intent = new Intent(this, MathService.class);
        start.setOnClickListener(view -> {
            bindService(intent, connection, Service.BIND_AUTO_CREATE);
            Toast.makeText(getApplicationContext(),"启动服务",Toast.LENGTH_SHORT).show();

        });
        stop.setOnClickListener(view -> {
            unbindService(connection);
            Toast.makeText(getApplicationContext(),"关闭服务",Toast.LENGTH_SHORT).show();
        });
        sum.setOnClickListener(view -> {
            int sum = binder.getSum(Integer.parseInt(input.getText().toString()));
            Toast.makeText(getApplicationContext(),"结果是："+sum,Toast.LENGTH_SHORT).show();
        });
    }
}